package com.sf.service.impl;

import com.sf.domain.Department;
import com.sf.ex.BusinessException;
import com.sf.mapper.DepartmentMapper;
import com.sf.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> list() {

        return departmentMapper.list();
    }

    @Override
    public void delete(Long id) {
        // 如果id 等于null, 抛出异常, 告诉前端id 不能为空
        if(id == null){
            throw new BusinessException("id 不能为空");
        }
        departmentMapper.delete(id);
    }

    @Override
    public void save( Department department) {
        departmentMapper.insert(department);
    }

    // 添加update方法实现修改功能
    @Override
    public void update(Department department) {
        // 校验必要参数
        if (department.getId() == null) {
            throw new BusinessException("修改操作必须指定ID");
        }
        if (department.getName() == null || department.getName().trim().isEmpty()) {
            throw new BusinessException("部门名称不能为空");
        }
        if (department.getSn() == null || department.getSn().trim().isEmpty()) {
            throw new BusinessException("部门编码不能为空");
        }

        // 调用mapper执行更新操作
        int rows = departmentMapper.update(department);
        if (rows == 0) {
            throw new BusinessException("修改失败，未找到对应部门或数据未变更");
        }
    }
}
